package com.sxhalo.fsms.controller.api;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.sxhalo.fsms.domain.*;
import com.sxhalo.fsms.service.IFactPatrolJobItemService;
import com.sxhalo.fsms.service.IFactPatrolJobService;
import com.sxhalo.fsms.service.IUserInfoService;
import com.sxhalo.fsms.util.CookieUtils;
import com.sxhalo.fsms.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxhalo.fsms.controller.BaseController;
import com.sxhalo.fsms.log.SysControllerLog;
import com.sxhalo.fsms.service.IUserPatrolRecordService;
import com.sxhalo.fsms.util.ApiResult;

@Controller
@RequestMapping("/api")
public class UserPatrolRecordController extends BaseController {
	
	@Autowired
	private IUserPatrolRecordService recService;
	@Autowired
	private IFactPatrolJobService jobService;
	@Autowired
	private IFactPatrolJobItemService jobItemService;

	@Autowired
	private IUserInfoService userService;

	@ResponseBody
	@RequestMapping(value = "/patrolrecord", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findPatrol(Integer typeId,Integer current, Integer pageSize, HttpServletRequest req) {
		String where = "1=1";
		String order = "create_time desc";
		if (!isBlank(req.getParameter("jobName"))) {
			where += " and job_name like '%" + req.getParameter("jobName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("userName"))) {
			String sel = " select user_id from user_info where real_name like '%" + req.getParameter("userName").trim() + "%'";
			where += " and patrol_user in (" + sel + ")";
		}
		if (!isBlank(req.getParameter("comment"))) {
			where += " and comment like '%" + req.getParameter("comment").trim() + "%'";
		}
		if (!isBlank(req.getParameter("dutyLeaderName"))) {
			where += " and duty_leader_name like '%" + req.getParameter("dutyLeaderName").trim() + "%'";
		}
		return findList(current, pageSize, where, order, recService);
	}

    @ResponseBody
    @RequestMapping(value = "/patrol/record", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
    public ApiResult findPatrolRecord(Integer jobId, HttpServletRequest req) {
        String token = CookieUtils.getCookieValue(req, "token");
        if (token != null) {
            Integer userId = TokenUtil.getUserId(token);
            //先查询是否有正在进行的巡检
            UserPatrolRecord record =recService.selectByWhere(" job_id ="+jobId +" and  patrol_user ="+userId +" and  patrol_time>=CURDATE()");
            List<FactPatrolJobItem> item=null;
           if(record==null){
			   FactPatrolJob job=  jobService.selectByPrimaryKey(jobId);
			   Timestamp nowtime = new Timestamp(System.currentTimeMillis());
			   record=new UserPatrolRecord();
			   record.setJobId(jobId);
			   record.setPatrolUser(userId);
			   record.setPatrolTime(nowtime);
			   record.setUpdateTime(nowtime);
			   record.setCreateTime(nowtime);
			   record.setJobName(job.getJobName() );
			   recService.insertSelective(record);
			   item=jobItemService.findWhereList(" delete_flag=0 and use_state=1 and job_id="+jobId,"`index`");
           }else{
			   item=jobItemService.getItemsRecordByJobId(record.getId(),jobId);
		   }
			Map<String, Object> body = new HashMap<>();
			body.put("record", record);
			body.put("sights", item);
            return ApiResult.retOK(req, body);
        } else {
            return ApiResult.retFail("401", "请登录");
        }

    }


    @ResponseBody
    @RequestMapping(value = "/patrolrecord/{id}", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findPatrolInfo(@PathVariable("id") Integer id, HttpServletRequest req) {
		UserPatrolRecord data = recService.selectByPrimaryKey(id);
		return ApiResult.retOK(req, data);
	}

	@ResponseBody
	@SysControllerLog(operationName = "新增用户巡检记录", modelName = "用户巡检记录")
	@RequestMapping(value = "/patrolrecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult savePatrol(@RequestBody UserPatrolRecord record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		Integer maxId = recService.getMaxId();
		record.setId(maxId + 1);
		record.setCreateTime(nowtime);
		record.setUpdateTime(nowtime);
		recService.insertSelective(record);
		return ApiResult.retOK(req);
	}
	
	@ResponseBody
	@SysControllerLog(operationName = "更新用户巡检记录", modelName = "用户巡检记录")
	@RequestMapping(value = "/patrolrecord", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult updatePatrol(@RequestBody UserPatrolRecord record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		recService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}
	
	
	@ResponseBody
	@SysControllerLog(operationName = "删除用户巡检记录", modelName = "用户巡检记录")
	@RequestMapping(value = "/patrolrecord", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult delPatrol(Integer id, HttpServletRequest req) {
		recService.deleteByPrimaryKey(id);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "确认巡检记录", modelName = "用户巡检记录")
	@RequestMapping(value = "/patrolrecord/conform", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult conformPatrol(@RequestBody UserPatrolRecord record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		String token = CookieUtils.getCookieValue(req, "token");
		if (token != null) {
			Integer userId = TokenUtil.getUserId(token);
			UserInfo user=userService.selectByPrimaryKey(userId);
			record.setDutyLeaderId(userId);
			record.setDutyLeaderName(user.getRealName());
		}
		record.setIsConform(1);
		recService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}

}
